package com.future.hedongjun.mine.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.future.baselib.activity.BaseActivity;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.DefaultFileResponse;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.entity.MessageEvent;
import com.future.baselib.http.HttpRequest;
import com.future.baselib.utils.EventBusUtil;
import com.future.baselib.utils.ImageUtils;
import com.future.baselib.utils.TxtUtils;
import com.future.baselib.view.ActionSheetDialog;
import com.future.baselib.view.CircleImageView;
import com.future.baselib.view.IosAlertDialog;
import com.future.hedongjun.R;
import com.future.hedongjun.common.Contant;
import com.future.hedongjun.common.MyApp;
import com.future.hedongjun.mine.bean.UserInfo;
import com.future.hedongjun.mine.bean.response.UserInfoResponse;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.utils.WechatClientNotExistException;

public class UserInfoActivity extends BaseActivity implements PlatformActionListener {

    @BindView(R.id.iv_icon)
    CircleImageView ivIcon;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_wechat)
    TextView tvWechat;
    @BindView(R.id.tv_weibo)
    TextView tvWeibo;
    @BindView(R.id.tv_qq)
    TextView tvQq;
    @BindView(R.id.iv_right_wechat)
    ImageView ivRightWechat;
    @BindView(R.id.iv_right_weibo)
    ImageView ivRightWeibo;
    @BindView(R.id.iv_right_qq)
    ImageView ivRightQq;
    private UserInfo info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
        setTitle("个人信息");
        info = MyApp.getInstance().getUserInfo();
        refreshView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUserInfo();
    }

    private void getUserInfo() {
        new HttpRequest<UserInfoResponse>()
                .with(this)
                .setPath("/api/User/getUserinfo")
                .addParam("token", MyApp.getInstance().getUserInfo().getToken())
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        MyApp.getInstance().setUserInfo(((UserInfoResponse) response).userInfo);
                        info = ((UserInfoResponse) response).userInfo;
                        refreshView();
                    }
                }).start(new UserInfoResponse());
    }


    private void refreshView() {
        Glide.with(this)
                .load(info.getAvatar())
                .apply(RequestOptions.placeholderOf(R.drawable.tab_wd_mr).dontAnimate())
                .into(ivIcon);
        tvName.setText(info.getNickname());
        tvPhone.setText(TxtUtils.hidePhoneMiddle(info.getMobile()));
        tvWechat.setText(info.getBind_wx() == 0 ? "未绑定" : "已绑定");
        if (info.getBind_wx() == 1) {
            ivRightWechat.setVisibility(View.GONE);
        }
        tvWeibo.setText(info.getBind_wb() == 0 ? "未绑定" : "已绑定");

        if (info.getBind_wb() == 1) {
            ivRightWeibo.setVisibility(View.GONE);
        }
        tvQq.setText(info.getBind_qq() == 0 ? "未绑定" : "已绑定");
        if (info.getBind_qq() == 1) {
            ivRightQq.setVisibility(View.GONE);
        }
    }

    private void choosePic() {
        ActionSheetDialog dialog = new ActionSheetDialog(this).builder()
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.BLACK, new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        PictureSelector.create(UserInfoActivity.this)
                                .openCamera(PictureMimeType.ofImage())
                                .enableCrop(false)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    }
                })
                .addSheetItem("相册", ActionSheetDialog.SheetItemColor.BLACK, new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        PictureSelector.create(UserInfoActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(1)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    }
                })
                .setCancelable(true)
                .setTitle("选择照片来源");
        dialog.show();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                uploadImg(selectList.get(0).getPath());
            }
        }

    }

    private void uploadImg(String photo) {
        new HttpRequest()
                .with(this)
                .setPath("/api/Common/upload")
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        changeIcon(((DefaultFileResponse) response).url);
                    }
                }).uploadFile(new File(photo));
    }

    private void changeIcon(String photoUrl) {//修改头像
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setPath("/api/User/profile")
                .addParam("token", MyApp.getInstance().getUserInfo().getToken())
                .addParam("avatar", photoUrl)
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        getUserInfo();
                    }
                }).start(new DefaultResponse());
    }

    @OnClick({R.id.layout_icon, R.id.layout_nickname, R.id.btn_logout, R.id.layout_phone, R.id.layout_wechat, R.id.layout_weibo, R.id.layout_qq})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_icon:
                choosePic();
                break;
            case R.id.layout_nickname:
                startActivityForResult(EditNicknameActivity.class, 0x321);
                break;
            case R.id.layout_phone:
                Bundle bundle1 = new Bundle();
                bundle1.putString("phone", info.getMobile());
                startActivityForResult(EditPhone1Activity.class, bundle1, 0x321);
                break;
            case R.id.layout_wechat:
                if (info.getBind_wx() == 0) {
                    Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                    wechat.setPlatformActionListener(this);
                    wechat.authorize();
                }
                break;
            case R.id.layout_weibo:
                if (info.getBind_wb() == 0) {
                    Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
                    weibo.setPlatformActionListener(this);
                    weibo.authorize();
                }
                break;
            case R.id.layout_qq:
                if (info.getBind_qq() == 0) {
                    Platform qq = ShareSDK.getPlatform(QQ.NAME);
                    qq.setPlatformActionListener(this);
                    qq.authorize();

                }
                break;
            case R.id.btn_logout:
                new IosAlertDialog(this)
                        .builder()
                        .setMsg("确定退出登录吗")
                        .setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                            }
                        })
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                logout();
                            }
                        }).show();
                break;
        }
    }

    private void logout() {
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setPath("/api/User/logout")
                .addParam("token", MyApp.getInstance().getUserInfo().getToken())
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        MyApp.getInstance().setUserInfo(null);
                        toast("退出登录成功");
                        setResult(RESULT_OK);
                        finish();
                        EventBusUtil.sendEvent(new MessageEvent(Contant.EVENT_CODE_LOGOUT));
                    }
                }).start(new DefaultResponse());
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        final PlatformDb db = platform.getDb();
        String token = db.getToken();
        String key = "";
        if (db.getPlatformNname().equals(QQ.NAME)) {
            key = "qq";
        } else if (db.getPlatformNname().equals(Wechat.NAME)) {
            key = "wechat";
        } else if (db.getPlatformNname().equals(SinaWeibo.NAME)) {
            key = "sina";
        }
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode("_bindmobile_001")
                .addParam(key, token)
                .addParam("userToken", MyApp.getInstance().getUserToken())
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        getUserInfo();
                    }
                }).start(new DefaultResponse());
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        if (throwable instanceof WechatClientNotExistException) {
            toast("微信客户端不存在");
        } else {
            toast(throwable.getMessage());
        }
    }

    @Override
    public void onCancel(Platform platform, int i) {
        toast("取消登录");
    }
}
